import {
	ITreeViewController,
	TreeViewActionType,
	IParam,
	ITreeViewAbility,
	ITreeViewStore,
	ITreeAbility,
	SearchFormActionType,
	IViewActionResult,
	ICtrlActionResult,
} from '@/core/interface';
import { MDViewController } from './md-view-controller';

/**
 * 树视图视图控制器
 *
 * @export
 * @class TreeViewController
 * @extends {ViewController}
 */
export class TreeViewController
	extends MDViewController<TreeViewActionType, ITreeViewStore, ITreeViewAbility>
	implements ITreeViewController<ITreeViewStore, ITreeViewAbility>
{
	/**
	 * 获取树部件能力
	 *
	 * @protected
	 * @return {*}  {(ITreeAbility | undefined)}
	 * @memberof TreeViewController
	 */
	protected getMDCtrlAbility(): ITreeAbility | undefined {
		const tree = this.model.ctrls.find(
			(ctrl: IParam) => ctrl.controlType === 'TREEVIEW'
		);
		if (tree) {
			return this.getSubAbility<ITreeAbility>(tree.name);
		}
		return undefined;
	}

	/**
	 * 快速分组值变化
	 *
	 * @param {IParam} item
	 * @memberof MDViewController
	 */
	public handleQuickGroupValueChange(item: IParam) {
		if (item) {
			this.queryParams.quickGroupData = item.data;
			const mdCtrl = this.getMDCtrlAbility();
			if (mdCtrl) {
				mdCtrl.refreshAllNode();
			}
		}
		this.isEmitQuickGroupValue = true;
	}

	/**
	 * 处理搜索表单部件行为
	 *
	 * @protected
	 * @param {SearchFormActionType} action
	 * @param {IParam[]} data
	 * @memberof TreeViewController
	 */
	protected handleSearchFormAction(
		action: SearchFormActionType,
		data: IParam[]
	) {
		const mdCtrl = this.getMDCtrlAbility();
		if (mdCtrl) {
			if (action === 'load') {
				mdCtrl.load();
			}
			if (action === 'search') {
				mdCtrl.refreshAllNode();
			}
		}
	}

	/**
	 * 搜索
	 *
	 * @param {string} searchValue
	 * @memberof TreeViewController
	 */
	public search(searchValue: string) {
		this.queryParams.query = searchValue;
		const mdCtrl = this.getMDCtrlAbility();
		if (mdCtrl) {
			mdCtrl.refreshAllNode({ query: searchValue });
		}
	}

	/**
	 * 刷新
	 *
	 * @param {(IParam | undefined)} [args]
	 * @return {*}  {Promise<IViewActionResult>}
	 * @memberof TreeViewController
	 */
	public refresh(args?: IParam | undefined): Promise<IViewActionResult> {
		const mdCtrl = this.getMDCtrlAbility();
		if (mdCtrl) {
			return new Promise((resolve: Function) => {
				mdCtrl
					.refreshAllNode({ query: this.queryParams.query })
					.then((result: ICtrlActionResult) => {
						resolve({
							ok: result.ok,
							data: result.data,
							rowData: result.rowData,
						});
					});
			});
		}
		return Promise.reject({
			ok: false,
			data: null,
			rowData: { status: 500 },
		});
	}
}
